<template>
  <el-dialog
    v-model="dialog.visible"
    title="设置浮动佣金比例"
    width="600px"
    @close="handleCloseDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="150px" class="form">
      <el-form-item label="浮动佣金比例	" prop="floatCommissionRatio">
        <el-input
          v-model="formData.floatCommissionRatio"
          placeholder="请输入浮动佣金比例"
          style="width: 260px"
        />
        <el-button>%</el-button>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCloseDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage } from "element-plus";
import MerchantUserAPI, { FloatCommissionRatioForm } from "@/api/user/merchantuser";
const emit = defineEmits(["update:modelValue", "loadData"]);

const dialog = reactive({
  title: "",
  visible: false,
});
const formRef = ref();
const defaultFormData: FloatCommissionRatioForm = {
  companyId: undefined,
  floatCommissionRatio: "",
};
const formData = ref({
  ...defaultFormData,
});

const formRules = reactive({
  floatCommissionRatio: [
    // { min: 1, max: 6, message: "佣金比例格式错误", trigger: "blur" },
    // { pattern: /^(?:-?0\.1|0)$/, message: "佣金比例格式错误，如-0.1，0.1" },
    { required: true, message: "请输入佣金比例", trigger: "blur" },
  ],
});
async function handleSubmit() {
  const validate = await formRef.value.validate();
  const data = JSON.parse(JSON.stringify(formData.value));
  data.floatCommissionRatio = (Number(data.floatCommissionRatio) / 100).toFixed(2);
  if (!validate) return;
  try {
    await MerchantUserAPI.updateFloatCommissionRatio({
      ...data,
    });
    ElMessage.success("成功");
    emit("loadData");
    handleCloseDialog();
  } catch (error) {
    console.log("error", error);
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  formData.value = Object.assign({}, formData.value, defaultFormData);
  emit("update:modelValue", false); // 关闭弹窗
}
function showModal(val) {
  const {
    companyId,
    merchantCompanyVO: { floatCommissionRatio },
  } = val;
  formData.value.floatCommissionRatio = (Number(floatCommissionRatio) * 100).toFixed(2);
  formData.value.companyId = companyId;
  dialog.visible = true;
}

defineExpose({
  showModal,
});
</script>
<style style="scss" scoped></style>
